//
//  LearningViewController.m
//  HotWord
//
//  Created by Rainbow on 1/15/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LearningViewController.h"
#import "LearningTableView.h"
#import "CacheData.h"
#import "MaskView.h"

@interface LearningViewController()

//把新的数据加载在新的卡片上
- (void)configurePage:(LearningTableView *)page forIndex:(NSUInteger)index;
//判断是否在显示
- (BOOL)isDisplayingPageForIndex:(NSUInteger)index;
//设置显示的滚动区域大小
- (CGRect)frameForPagingScrollView;
//设置每个卡片的位置和大小
- (CGRect)frameForPageAtIndex:(NSUInteger)index;
//设置所有卡片的scrollView的大小
- (CGSize)contentSizeForPagingScrollView;
//计算哪些需要显示，哪些不需要显示
- (void)tilePages;
//回收卡片
- (LearningTableView *)dequeueRecycledPage;

@end

@implementation LearningViewController
@synthesize pageLabel;
@synthesize pageLabel2;
@synthesize pagedScrollView;
@synthesize sessionStartView;
@synthesize sessionEndView;
@synthesize words;
@synthesize currentIndex;


@synthesize blackCircle1;
@synthesize blackCircle2;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.currentIndex = [[CacheData sharedData].selectedLetter.learnIndex intValue];
    self.words = [CacheData sharedData].selectedLetter.words;
 
    self.pagedScrollView.top = 480;
    self.pageLabel.alpha = 0;
    self.pageLabel2.alpha = 0;
    
    self.blackCircle1.frame = CGRectMake(0, 75, 0, 0);
    self.blackCircle2.frame = CGRectMake(0, 200, 0, 0);

    
    self.pagedScrollView.showsVerticalScrollIndicator = NO;
    recycledPages = [[NSMutableSet alloc] init];
    visiblePages  = [[NSMutableSet alloc] init];
    
    pagedScrollView.contentSize = [self contentSizeForPagingScrollView];
    //offsect表示第一个卡片到现在的卡片的距离
    [self.pagedScrollView setContentOffset:CGPointMake(currentIndex * self.pagedScrollView.width, 0)];
    if (self.currentIndex == 0) {
        self.sessionStartView.alpha = 1;
    }
    if (self.currentIndex >= [self.words count] - 1) {
        self.sessionEndView.alpha = 1;
    }
    if (self.words != nil) {
        [self tilePages];
    }
    self.pageLabel.text = [NSString stringWithFormat:@"%d", self.currentIndex + 1];
    self.pageLabel2.text = [NSString stringWithFormat:@"%d", [self.words count]];

}

- (void)viewDidUnload
{
    [self setPageLabel:nil];
    [self setPageLabel2:nil];
    [self setPagedScrollView:nil];
    [self setSessionStartView:nil];
    [self setSessionEndView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewDidAppear:(BOOL)animated
{
    MaskView *maskView = [[[MaskView alloc] init] autorelease];
    maskView = [[[NSBundle mainBundle] loadNibNamed:@"MaskView" owner:self options:nil] objectAtIndex:0];
    [self.view addSubview:maskView];
    maskView.frame = CGRectMake(0, 330, 320, 150);
    [self.view bringSubviewToFront:maskView];
    maskView.alpha = 1;
    
    [super viewDidAppear:animated];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.5f];
    self.pagedScrollView.top = 0;
    self.pageLabel.alpha = 1;
    self.pageLabel2.alpha = 1;
    self.blackCircle1.frame = CGRectMake(-50, 25, 100, 100);
    self.blackCircle2.frame = CGRectMake(-50, 150, 100, 100);
    [UIView commitAnimations];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)tilePages 
{
    // Calculate which pages are visible
    //srollView的bounds表示相对于整个scrollView的当前点，而不是相对于屏幕的位置
    CGRect visibleBounds = pagedScrollView.bounds;
    //算前一页的index
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds)) - 1;
    int lastNeededPageIndex  = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds)) + 1;
    
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex  = MIN(lastNeededPageIndex, [self.words count] - 1);
    
    //对于在visiblepage中的page
    for (LearningTableView *page in visiblePages) {
        if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
            [page reset];
            [recycledPages addObject:page];
            [page removeFromSuperview];
        }
    }
    //minusSet表示先做两个set的交集，然后从visible里面减去这个交集
    [visiblePages minusSet:recycledPages];
    
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            LearningTableView *page = [self dequeueRecycledPage];
            if (page == nil) {
                page = [[[NSBundle mainBundle] loadNibNamed:@"LearningTableView" owner:self options:nil] objectAtIndex:0];
            }
            [self configurePage:page forIndex:index];
            [pagedScrollView addSubview:page];
            [visiblePages addObject:page];
        }
    } 
}

- (LearningTableView *)dequeueRecycledPage
{
    //anyObject返回recycle中的任何一个，如果有。如果没有，返回nil
    LearningTableView *page = [recycledPages anyObject];
    if (page) {
        [[page retain] autorelease];
        [recycledPages removeObject:page];
    }
    return page;
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    BOOL foundPage = NO;
    for (LearningTableView *page in visiblePages) {
        if (page.index == index) {
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}

- (void)configurePage:(LearningTableView *)page forIndex:(NSUInteger)index
{
    Word *word = [[CacheData sharedData] getWordByIndex:index];
    page.index = index;
    page.frame = [self frameForPageAtIndex:index];
    [page updateWord:word];
    
}

#pragma mark -
#pragma mark ScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self tilePages];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.currentIndex = self.pagedScrollView.contentOffset.x/self.pagedScrollView.bounds.size.width;
    self.pageLabel.text = [NSString stringWithFormat:@"%d", self.currentIndex + 1];
    [CacheData sharedData].selectedLetter.learnIndex = [NSNumber numberWithInt:self.currentIndex];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    if (self.currentIndex == 0) {
        self.sessionStartView.alpha = 1;
    }
    else
    {
        self.sessionStartView.alpha = 0;
    }
    
    if (self.currentIndex >= [self.words count] - 1) {
        self.sessionEndView.alpha = 1;
    }
    else
    {
        self.sessionEndView.alpha = 0;
    }
    [UIView commitAnimations];
}

#pragma mark -
#pragma mark  Frame calculations
#define PADDING  20

- (CGRect)frameForPagingScrollView {
    CGRect frame = [[UIScreen mainScreen] bounds];
    frame.origin.x -= PADDING;
    frame.size.width += (2 * PADDING);
    return frame;
}

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
    // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
    // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
    // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
    // because it has a rotation transform applied.
    CGRect bounds = pagedScrollView.bounds;
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + PADDING;
    return pageFrame;
}

- (CGSize)contentSizeForPagingScrollView {
    // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
    CGRect bounds = pagedScrollView.bounds;
    return CGSizeMake(bounds.size.width * [self.words count], bounds.size.height);
}


- (void)dealloc {
    [words release];
    [pageLabel release];
    [pageLabel2 release];
    [pagedScrollView release];
    [sessionStartView release];
    [sessionEndView release];
    [blackCircle1 release];
    [blackCircle2 release];
    [super dealloc];
}
@end
